{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.sys.path.append(os.path.dirname(os.path.abspath('.')))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 数据准备"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])\n",
    "y = np.array([1, 2, 3, 4])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# k-fold\n",
    "迭代方式实现KFold很简单，不断地更改测试集的位置即可，剩余的位置就构成训练集，如下所示："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 2 3] [0]\n",
      "[0 2 3] [1]\n",
      "[0 1 3] [2]\n"
     ]
    }
   ],
   "source": [
    "K = 3    # fold数\n",
    "test_size = len(X)//K    # 测试集尺寸\n",
    "idx_arr = np.arange(len(X))    # 生成索引数组\n",
    "\n",
    "for epoch in range(K):\n",
    "    test_idx = idx_arr[epoch*test_size:(epoch+1)*test_size]\n",
    "    train_idx = np.append(idx_arr[0:epoch*test_size],\n",
    "                          idx_arr[(epoch+1)*test_size:])    # 利用切片不会越界的性质\n",
    "    print(train_idx, test_idx)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "生成器方式："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 2 3] [0]\n",
      "[0 2 3] [1]\n",
      "[0 1 3] [2]\n"
     ]
    }
   ],
   "source": [
    "K = 3\n",
    "test_size = len(X)//K\n",
    "idx_arr = np.arange(len(X))\n",
    "gen = ((np.append(idx_arr[0:epoch*test_size], idx_arr[(epoch+1)*test_size:]),\n",
    "        idx_arr[epoch*test_size:(epoch+1)*test_size]) for epoch in range(K))\n",
    "\n",
    "for train, test in gen:\n",
    "    print(train, test)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Stratified k-fold\n",
    "当数据目标值为类别型数据时，分层抽样是最佳选择，在每个类别下都分别做k-fold。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [],
   "source": [
    "X = np.ones(10)\n",
    "y = np.array([0, 0, 0, 0, 1, 1, 1, 1, 1, 1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2 3 7 8 9] [0 1 4 5 6]\n",
      "[0 1 4 5 6] [2 3 7 8 9]\n"
     ]
    }
   ],
   "source": [
    "K = 2\n",
    "n_samples = len(y)\n",
    "\n",
    "for epoch in range(K):\n",
    "    # 空索引，等待扩展\n",
    "    train_idx = np.array(list()).astype(int)\n",
    "    test_idx = np.array(list()).astype(int)\n",
    "\n",
    "    # 遍历y所有可能的取值并扩展索引\n",
    "    for y_val in np.unique(y):\n",
    "        idxs = np.arange(n_samples)[y == y_val]    # 当前类别下的全部索引\n",
    "        test_size = len(idxs)//K\n",
    "        train_idx = np.append(train_idx, np.append(\n",
    "            idxs[0:epoch*test_size], idxs[(epoch+1)*test_size:]))\n",
    "        test_idx = np.append(\n",
    "            test_idx, idxs[epoch*test_size:(epoch+1)*test_size])\n",
    "    print(train_idx, test_idx)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "hide_input": false,
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
